<?php

namespace App\Services;

use Illuminate\Support\Facades\DB;
use App\Models\Answer;
use App\Models\PartnerUser;
use App\Models\Question;
use App\Models\User;
use App\Models\Profile;
use common\utils\RSACrypt;


class UserService
{
    /**
     * 获取用户信息，用户表
     */
    public static function getUserBaseInfo(int $id)
    {
        return User::where(['id'=>$id])->get()->first()->toArray();
    }


    /**
     * 获取用户信息，用户表
     */
    public static function getUsersInfo($ids)
    {
        return User::whereIn('id',$ids)->get()->toArray();
    }

    /**
     * 获取用户安全问题答案
     *
     * @param int $id
     * @return array
     */
    public static function getAnswer($id, $user_type)
    {
        if (empty($id)) {
            return [];
        }
        $answer = Answer::where(['user_id' => $id, 'user_type' => $user_type])->toArray();

        $question = Question::where(['id' => $answer['question_id']])->first();
        $answer['question'] = $question['question'];

        return $answer;
    }

    /**
     * 获取身份证号码
     */
    public static function getIdcard($user_id)
    {
        $model = Profile::where(['user_id' => $user_id])->first();

        $number = $model['idcard'];

        $number = empty($number) ? $number : current($number);
        $number = RSACrypt::rsaDecrypt($number);

        if (is_numeric($number)) {
            $number = '****' . substr($number, -4);
            $number = "你已通过实名认证。身份证号码($number)";
        } else {
            $number = "你已通过实名认证。身份证号码($number)";
        }
        return $number;
    }

    /**
     * 获取用户信息和相关代理信息
     */
    public static function getUserAgentInfoByApiName($apiUserName)
    {

        $user = DB::table('user as u')->select(DB::raw("u.id, u.username, u.agent_id, u.agent_name"))
            ->leftJoin('partner_user as g', 'u.id', '=', 'g.user_id')
            ->where(['g.partner_username' => $apiUserName])
            ->first();
        if(!empty($user)){
//            return $user->toArray();
            return json_decode(json_encode($user,320),true);
        }
        return $user;
    }

    /**
     * 根据 userIDs 批量获取用户信息
     */
    public static function getUserInfoByIDs($userIDs)
    {
        // $sql = "select id, `name` from user where id in (". implode(',', $userIdArr) .")";
        // $userNameList = $coreDb->query($sql); 
        return User::select("id, name")->where(['in', 'id', [implode(',', $userIDs)]])->get()->toArray();
    }
}
